package plugin

import (
	"fmt"
	"github.com/zhongshaofa/swan-jobs/configs"
	"github.com/zhongshaofa/swan-jobs/internal/services/gorm_logger"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"os"
)

var DB *gorm.DB

func ModelSetup() *gorm.DB {
	if DB != nil {
		return DB
	}

	if configs.AppConfig == nil {
		fmt.Println("Fail to AppConfig not load!")
		os.Exit(1)
	}

	if configs.DatabaseConfig == nil {
		fmt.Println("Fail to DatabaseConfig not load!")
		os.Exit(1)
	}

	level := logger.Warn
	if configs.AppConfig.Debug {
		level = logger.Info
	}
	gormLogger := gorm_logger.NewGormLogger(Logger, level)

	gormLogger.SetAsDefault()

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		configs.DatabaseConfig.Username,
		configs.DatabaseConfig.Password,
		configs.DatabaseConfig.Host,
		configs.DatabaseConfig.Port,
		configs.DatabaseConfig.DbName,
	)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{Logger: gormLogger})

	if err != nil {
		panic(fmt.Sprintf("数据库连接失败：%s", err))
	}

	sqlDb, _ := db.DB()
	sqlDb.SetMaxIdleConns(configs.DatabaseConfig.MaxIdleConnNumber)
	sqlDb.SetMaxOpenConns(configs.DatabaseConfig.MaxOpenConnNumber)

	DB = db
	return DB
}
